// API基础配置
const API_BASE_URL = 'http://localhost:8081/api'

// 通用请求方法
class ApiService {
  constructor() {
    this.baseURL = API_BASE_URL
  }

  // 通用请求方法
  async request(url, options = {}, retryCount = 0) {
    const maxRetries = 3
    const retryDelay = 1000 // 1秒
    
    // 获取认证token
    const token = localStorage.getItem('token')
    
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Connection': 'keep-alive',
        ...(token && { 'Authorization': `Bearer ${token}` }),
        ...options.headers
      },
      ...options
    }

    try {
      console.log(`发起API请求: ${this.baseURL}${url}`)
      console.log(`请求配置:`, {
        method: config.method || 'GET',
        headers: config.headers,
        body: config.body ? (() => { try { return JSON.parse(config.body) } catch(_) { return config.body } })() : undefined
      })
      const response = await fetch(`${this.baseURL}${url}`, config)
      console.log(`API响应状态: ${response.status} ${response.statusText}`)

      // 读取一次响应文本并缓存，避免重复读取导致的流已消费问题
      const rawText = await response.text()

      if (!response.ok) {
        // 优先解析为JSON以获取 message 字段
        let message = `HTTP ${response.status}: ${response.statusText}`
        try {
          const errJson = rawText ? JSON.parse(rawText) : {}
          console.log('错误响应JSON:', errJson)
          message = errJson.message || errJson.error || message
        } catch (_) {
          console.log('错误响应文本:', rawText)
          if (rawText) message = rawText
        }
        throw new Error(message)
      }

      // 成功响应：依据 content-type 判断解析方式
      const contentType = response.headers.get('content-type') || ''
      if (contentType.includes('application/json')) {
        try {
          const data = rawText ? JSON.parse(rawText) : {}
          console.log('API响应数据:', data)
          return data
        } catch (_) {
          // 非严格JSON时回落为文本
          console.log('API响应文本(非严格JSON):', rawText)
          return { message: rawText, success: true }
        }
      }
      console.log('API响应文本:', rawText)
      return { message: rawText, success: true }
    } catch (error) {
      console.error('API请求失败:', error)
      
      // 如果是网络错误且还有重试次数，则重试
      if (retryCount < maxRetries && this.shouldRetry(error)) {
        console.log(`请求失败，${retryDelay}ms后重试 (${retryCount + 1}/${maxRetries})`)
        await this.delay(retryDelay * (retryCount + 1))
        return this.request(url, options, retryCount + 1)
      }
      
      // 提供更友好的错误信息
      if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
        throw new Error('后端服务未启动，请启动后端服务')
      }
      
      if (error.message.includes('ERR_INCOMPLETE_CHUNKED_ENCODING')) {
        throw new Error('网络连接中断，请检查网络连接或稍后重试')
      }
      
      // 处理HTTP 400错误
      if (error.message.includes('HTTP 400')) {
        throw new Error('请求参数错误，请检查输入信息')
      }
      
      // 处理其他常见的网络错误
      if (error.message.includes('ERR_NETWORK')) {
        throw new Error('网络连接失败，请检查网络连接')
      }
      
      if (error.message.includes('ERR_CONNECTION_REFUSED')) {
        throw new Error('后端服务未启动，请启动后端服务')
      }
      
      throw error
    }
  }
  
  // 判断是否应该重试
  shouldRetry(error) {
    return (
      error.name === 'TypeError' ||
      error.message.includes('Failed to fetch') ||
      error.message.includes('ERR_INCOMPLETE_CHUNKED_ENCODING') ||
      error.message.includes('网络连接中断')
    )
  }
  
  // 延迟函数
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  // GET请求
  async get(url, params = {}) {
    const queryString = new URLSearchParams(params).toString()
    const fullUrl = queryString ? `${url}?${queryString}` : url
    return this.request(fullUrl, { method: 'GET' })
  }

  // POST请求
  async post(url, data = {}) {
    return this.request(url, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // PUT请求
  async put(url, data = {}) {
    return this.request(url, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  }

  // DELETE请求
  async delete(url) {
    return this.request(url, { method: 'DELETE' })
  }
}

// 认证API
export class AuthAPI extends ApiService {
  // 用户注册
  async register(userData) {
    return this.post('/auth/register', userData)
  }

  // 用户登录
  async login(credentials) {
    return this.post('/auth/login', credentials)
  }

  // 检查用户名
  async checkUsername(username) {
    return this.get('/auth/check-username', { username })
  }

  // 检查邮箱
  async checkEmail(email) {
    return this.get('/auth/check-email', { email })
  }
}

// 用户管理API
export class UserAPI extends ApiService {
  // 获取所有用户
  async getUsers() {
    return this.get('/users')
  }

  // 获取所有用户（管理员专用）
  async getAllUsers() {
    return this.get('/users')
  }

  // 获取用户详情
  async getUser(id) {
    return this.get(`/users/${id}`)
  }

  // 更新用户信息
  async updateUser(id, userData) {
    return this.put(`/users/${id}`, userData)
  }

  // 更新密码
  async updatePassword(id, passwordData) {
    return this.put(`/users/${id}/password`, passwordData)
  }

  // 更新用户状态
  async updateUserStatus(id, statusData) {
    return this.put(`/users/${id}/status`, statusData)
  }

  // 更新用户角色
  async updateUserRole(id, roleData) {
    return this.put(`/users/${id}/role`, roleData)
  }

  // 上传用户头像
  async uploadAvatar(id, file) {
    const formData = new FormData()
    formData.append('avatar', file)

    console.log('上传头像请求:', {
      userId: id,
      fileName: file.name,
      fileSize: file.size,
      fileType: file.type,
      endpoint: `/users/${id}/avatar`
    })

    return this.request(`/users/${id}/avatar`, {
      method: 'POST',
      body: formData,
      headers: {
        // 不设置Content-Type，让浏览器自动设置multipart/form-data
        'Accept': 'application/json'
      }
    })
  }

  // 获取头像URL
  getAvatarUrl(filename) {
    const url = `${this.baseURL}/users/avatars/${filename}`
    console.log('构建头像URL:', url)
    return url
  }
}

// 设备管理API
export class DeviceAPI extends ApiService {
  // 获取用户设备
  async getUserDevices(userId) {
    return this.get(`/devices/user/${userId}`)
  }

  // 创建设备
  async createDevice(deviceData) {
    return this.post('/devices', deviceData)
  }

  // 获取设备详情
  async getDevice(id) {
    return this.get(`/devices/${id}`)
  }

  // 更新设备信息
  async updateDevice(id, deviceData) {
    return this.put(`/devices/${id}`, deviceData)
  }

  // 控制设备
  async controlDevice(id, controlData) {
    return this.put(`/devices/${id}/control`, controlData)
  }

  // 更新设备属性
  async updateDeviceProperties(id, properties) {
    return this.put(`/devices/${id}/properties`, { properties })
  }

  // 根据房间获取设备
  async getDevicesByRoom(userId, room) {
    return this.get(`/devices/user/${userId}/room/${room}`)
  }

  // 根据状态获取设备
  async getDevicesByStatus(userId, status) {
    return this.get(`/devices/user/${userId}/status/${status}`)
  }

  // 获取用户房间列表
  async getUserRooms(userId) {
    return this.get(`/devices/user/${userId}/rooms`)
  }

  // 删除设备
  async deleteDevice(id) {
    return this.delete(`/devices/${id}`)
  }

  // 获取设备控制记录
  async getDeviceLogs(deviceId, page = 0, size = 10) {
    return this.get(`/devices/${deviceId}/logs/page?page=${page}&size=${size}`)
  }
}

// 真实设备控制API
export class RealDeviceAPI extends ApiService {
  // 执行设备控制命令
  async controlDevice(deviceId, commandData) {
    return this.post(`/real-devices/${deviceId}/control`, commandData)
  }

  // 获取设备状态
  async getDeviceStatus(deviceId) {
    return this.get(`/real-devices/${deviceId}/status`)
  }

  // 检查设备在线状态
  async checkDeviceOnline(deviceId) {
    return this.get(`/real-devices/${deviceId}/online`)
  }

  // 测试设备连接
  async testDeviceConnection(deviceId) {
    return this.post(`/real-devices/${deviceId}/test-connection`)
  }

  // 获取设备支持的指令
  async getDeviceCommands(deviceId) {
    return this.get(`/real-devices/${deviceId}/commands`)
  }

  // 获取设备属性
  async getDeviceProperties(deviceId) {
    return this.get(`/real-devices/${deviceId}/properties`)
  }

  // 设置设备属性
  async setDeviceProperties(deviceId, properties) {
    return this.put(`/real-devices/${deviceId}/properties`, properties)
  }
}

// 智能灯光控制API
export class SmartLightAPI extends ApiService {
  // 灯光开关控制
  async switchLight(deviceId, on, userId) {
    return this.post(`/real-devices/${deviceId}/light/switch`, { on, userId })
  }

  // 灯光亮度控制
  async setBrightness(deviceId, brightness, userId) {
    return this.post(`/real-devices/${deviceId}/light/brightness`, { brightness, userId })
  }
}

// 智能温控器控制API
export class SmartThermostatAPI extends ApiService {
  // 温度控制
  async setTemperature(deviceId, temperature, userId) {
    return this.post(`/real-devices/${deviceId}/thermostat/temperature`, { temperature, userId })
  }
}

// 智能摄像头控制API
export class SmartCameraAPI extends ApiService {
  // 摄像头开关控制
  async switchCamera(deviceId, on, userId) {
    return this.post(`/real-devices/${deviceId}/camera/switch`, { on, userId })
  }

  // 开始/停止录像
  async controlRecording(deviceId, action, userId) {
    return this.post(`/real-devices/${deviceId}/camera/record`, { record: action === 'start', userId })
  }

  // 拍照
  async takePhoto(deviceId, userId, options = {}) {
    return this.post(`/real-devices/${deviceId}/camera/snapshot`, { userId, ...options })
  }

  // 调整摄像头水平角度
  async adjustPan(deviceId, angle, userId) {
    return this.post(`/real-devices/${deviceId}/camera/pan`, { angle, userId })
  }

  // 调整摄像头垂直角度
  async adjustTilt(deviceId, angle, userId) {
    return this.post(`/real-devices/${deviceId}/camera/tilt`, { angle, userId })
  }

  // 设置摄像头分辨率
  async setResolution(deviceId, resolution, userId) {
    return this.post(`/real-devices/${deviceId}/camera/resolution`, { resolution, userId })
  }

  // 设置夜视模式
  async setNightVision(deviceId, enabled, userId) {
    return this.post(`/real-devices/${deviceId}/camera/night-vision`, { enabled, userId })
  }

  // 获取摄像头状态
  async getCameraStatus(deviceId) {
    return this.get(`/real-devices/${deviceId}/camera/status`)
  }

  // 获取录像列表
  async getRecordingList(deviceId, page = 0, size = 10) {
    return this.get(`/real-devices/${deviceId}/camera/recordings?page=${page}&size=${size}`)
  }

  // 获取实时视频流URL
  async getVideoStreamUrl(deviceId) {
    return this.get(`/real-devices/${deviceId}/camera/stream-url`)
  }

  // 开始巡航
  async startPatrol(deviceId, userId) {
    return this.post(`/real-devices/${deviceId}/camera/patrol/start`, { userId })
  }

  // 停止巡航
  async stopPatrol(deviceId, userId) {
    return this.post(`/real-devices/${deviceId}/camera/patrol/stop`, { userId })
  }
}

// 设备状态同步API
export class DeviceStatusAPI extends ApiService {
  // 手动同步设备状态
  async syncDeviceStatus(deviceId) {
    return this.post(`/device-status/${deviceId}/sync`)
  }

  // 批量同步设备状态
  async batchSyncDeviceStatus(deviceIds) {
    return this.post('/device-status/batch-sync', deviceIds)
  }

  // 获取设备状态统计
  async getDeviceStatusStats() {
    return this.get('/device-status/stats')
  }
}

// 设备控制测试API
export class DeviceTestAPI extends ApiService {
  // 测试设备控制器注册
  async testControllers() {
    return this.get('/test/device-control/controllers')
  }

  // 测试设备协议注册
  async testProtocols() {
    return this.get('/test/device-control/protocols')
  }

  // 测试设备控制命令
  async testDeviceCommand(deviceId, commandData) {
    return this.post(`/test/device-control/${deviceId}/test-command`, commandData)
  }

  // 测试设备状态获取
  async testDeviceStatus(deviceId) {
    return this.get(`/test/device-control/${deviceId}/test-status`)
  }

  // 测试设备连接
  async testDeviceConnection(deviceId) {
    return this.get(`/test/device-control/${deviceId}/test-connection`)
  }

  // 测试设备属性
  async testDeviceProperties(deviceId) {
    return this.get(`/test/device-control/${deviceId}/test-properties`)
  }

  // 测试设备指令
  async testDeviceCommands(deviceId) {
    return this.get(`/test/device-control/${deviceId}/test-commands`)
  }
}

// 场景管理API
export class SceneAPI extends ApiService {
  // 获取用户场景
  async getUserScenes(userId) {
    return this.get(`/scenes/user/${userId}`)
  }

  // 创建场景
  async createScene(sceneData) {
    return this.post('/scenes', sceneData)
  }

  // 执行场景
  async executeScene(id, userId) {
    return this.post(`/scenes/${id}/execute`, { userId })
  }

  // 添加设备到场景
  async addDeviceToScene(sceneId, deviceData) {
    return this.post(`/scenes/${sceneId}/devices`, deviceData)
  }

  // 获取场景设备
  async getSceneDevices(sceneId) {
    return this.get(`/scenes/${sceneId}/devices`)
  }

  // 更新场景状态
  async updateSceneStatus(id, isActive) {
    return this.put(`/scenes/${id}/status`, { isActive })
  }

  // 删除场景
  async deleteScene(id) {
    return this.delete(`/scenes/${id}`)
  }
}

// 设备类型API
export class DeviceTypeAPI extends ApiService {
  // 获取所有设备类型
  async getDeviceTypes() {
    return this.get('/device-types')
  }

  // 创建设备类型
  async createDeviceType(typeData) {
    return this.post('/device-types', typeData)
  }

  // 获取设备类型详情
  async getDeviceType(id) {
    return this.get(`/device-types/${id}`)
  }
}

// 首页数据API
export class HomeAPI extends ApiService {
  // 获取用户首页数据
  async getDashboard(userId) {
    return this.get(`/home/dashboard/${userId}`)
  }

  // 获取系统状态
  async getSystemStatus() {
    return this.get('/home/system-status')
  }
}

// 服务申请API
export class ServiceRequestAPI extends ApiService {
  // 获取所有服务申请
  async getAllServiceRequests(page = 0, size = 10) {
    return this.get(`/api/service-requests?page=${page}&size=${size}`)
  }

  // 获取紧急服务申请
  async getUrgentServiceRequests() {
    return this.get('/api/service-requests/urgent')
  }

  // 获取用户服务申请
  async getUserServiceRequests(userId) {
    return this.get(`/api/service-requests/user/${userId}`)
  }

  // 获取用户服务申请（分页）
  async getUserServiceRequestsPage(userId, page = 0, size = 50) {
    return this.get(`/api/service-requests/user/${userId}/page?page=${page}&size=${size}`)
  }

  // 创建服务申请
  async createServiceRequest(serviceData) {
    return this.post('/api/service-requests', serviceData)
  }

  // 更新服务申请状态
  async updateServiceStatus(id, statusData) {
    return this.put(`/api/service-requests/${id}/status`, statusData)
  }

  // 完成服务申请
  async completeService(id, completeData = {}) {
    return this.put(`/api/service-requests/${id}/complete`, completeData)
  }

  // 取消服务申请
  async cancelService(id) {
    return this.put(`/api/service-requests/${id}/cancel`)
  }

  // 删除服务申请
  async deleteServiceRequest(id) {
    return this.delete(`/api/service-requests/${id}`)
  }

  // 获取服务申请统计
  async getServiceRequestStats() {
    return this.get('/api/service-requests/stats')
  }
}

// 管理员API
export class AdminAPI extends ApiService {
  // 获取管理员仪表板统计数据
  async getDashboardStats() {
    return this.get('/api/admin/dashboard/stats')
  }

  // 获取所有用户（管理员专用）
  async getAllUsers() {
    return this.get('/api/admin/users')
  }

  // 获取所有设备（管理员专用）
  async getAllDevices() {
    return this.get('/api/admin/devices')
  }

  // 获取所有服务申请（管理员专用）
  async getAllServiceRequests() {
    return this.get('/api/admin/service-requests')
  }
}

// 创建API实例
export const authAPI = new AuthAPI()
export const userAPI = new UserAPI()
export const deviceAPI = new DeviceAPI()
export const realDeviceAPI = new RealDeviceAPI()
export const smartLightAPI = new SmartLightAPI()
export const smartThermostatAPI = new SmartThermostatAPI()
export const smartCameraAPI = new SmartCameraAPI()
export const deviceStatusAPI = new DeviceStatusAPI()
export const deviceTestAPI = new DeviceTestAPI()
export const sceneAPI = new SceneAPI()
export const deviceTypeAPI = new DeviceTypeAPI()
export const homeAPI = new HomeAPI()
export const serviceRequestAPI = new ServiceRequestAPI()
export const adminAPI = new AdminAPI()

// 默认导出
export default {
  authAPI,
  userAPI,
  deviceAPI,
  realDeviceAPI,
  smartLightAPI,
  smartThermostatAPI,
  smartCameraAPI,
  deviceStatusAPI,
  deviceTestAPI,
  sceneAPI,
  deviceTypeAPI,
  homeAPI,
  serviceRequestAPI,
  adminAPI
}
